//--------------------------------------------------------------------------------------
// File: Tutorial07.cpp
//
// This application demonstrates texturing
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include <windows.h>
#include <d3d11.h>
#include <d3dx11.h>
#include <d3dcompiler.h>
#include <xnamath.h>
#include "resource.h"
#include <Camera.h>
#include <d3d9.h>
#include <VoxelTerrain.h>
#include <D3DVoxelChunk.h>
#include <dinput.h>
#include <D3D11SDKLayers.h>
#include <sys/timeb.h>
#include <stdio.h>
#include "DXDevice.h"
#pragma comment( lib, "d3d9.lib" )
#pragma comment (lib, "dinput8.lib")
#pragma comment (lib, "dxguid.lib")
//#include <DXUTmisc.h>
//--------------------------------------------------------------------------------------
// Structures
//--------------------------------------------------------------------------------------

struct ViewMatrix
{
    D3DXMATRIX mView;
};

struct CBChangeOnResize
{
    D3DXMATRIX mProjection;
};




//--------------------------------------------------------------------------------------
// Global Variables
//--------------------------------------------------------------------------------------
HINSTANCE                           g_hInst = NULL;
HWND                                g_hWnd = NULL;


D3D_DRIVER_TYPE                     g_driverType = D3D_DRIVER_TYPE_NULL;
D3D_FEATURE_LEVEL                   g_featureLevel = D3D_FEATURE_LEVEL_11_0;
ID3D11Device*						g_pd3dDevice = NULL;
ID3D11DeviceContext*				g_pImmediateContext = NULL;
IDXGISwapChain*						g_pSwapChain = NULL;
ID3D11RenderTargetView*				g_pRenderTargetView = NULL;
ID3D11Texture2D*					g_pDepthStencil = NULL;
ID3D11DepthStencilView*				g_pDepthStencilView = NULL;
ID3D11InfoQueue *					g_pInfoQueue = NULL; 

ID3D11Buffer*						g_matViewMatrixBuffer = NULL;
ID3D11Buffer*                       g_matProjectionMatrixBuffer = NULL;

//XMFLOAT4                            g_vMeshColor( 0.7f, 0.7f, 0.7f, 1.0f );
VoxelTerrain *						g_pVoxelTerrain;
Camera *g_pCamera = NULL;

LPDIRECTINPUT8 din;    // the pointer to our DirectInput interface
LPDIRECTINPUTDEVICE8 dinkeyboard;    // the pointer to the keyboard device

LPDIRECTINPUTDEVICE8 dinmouse;    // the pointer to the mouse device

//typedef struct DIMOUSESTATE
//{
//    LONG lX;
//    LONG lY;
//    LONG lZ;
//    BYTE rgbButtons[4];
//} DIMOUSESTATE, *LPDIMOUSESTATE;

BYTE keystate[256];    // the storage for the key-information
DIMOUSESTATE mousestate;    // the storage for the mouse-information


void initDInput(HINSTANCE hInstance, HWND hWnd);    // sets up and initializes DirectInput
void detect_input(void);    // gets the current input state
void cleanDInput(void);    // closes DirectInput and releases memory


//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow );
HRESULT InitDevice();
void CleanupDevice();
LRESULT CALLBACK    WndProc( HWND, UINT, WPARAM, LPARAM );
void Render();


//--------------------------------------------------------------------------------------
// Entry point to the program. Initializes everything and goes into a message processing 
// loop. Idle time is used to render the scene.
//--------------------------------------------------------------------------------------
int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow )
{
    UNREFERENCED_PARAMETER( hPrevInstance );
    UNREFERENCED_PARAMETER( lpCmdLine );

    if( FAILED( InitWindow( hInstance, nCmdShow ) ) )
        return 0;

	initDInput(hInstance, g_hWnd);
    if( FAILED( InitDevice() ) )
    {
        CleanupDevice();
        return 0;
    }

    // Main message loop
    MSG msg = {0};
	
	char *fpsString = new char[100];

	struct _timeb timebuffer;
	_ftime( &timebuffer );
	unsigned short startTime;

	int oneSecond = 1000;
	short count = 0;
    while( WM_QUIT != msg.message )
    {

		startTime = timebuffer.millitm;
		detect_input();
        if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
        {
            TranslateMessage( &msg );
            DispatchMessage( &msg );
        }
        else
        {
            Render();
        }

		_ftime( &timebuffer );
		unsigned short currentTime = timebuffer.millitm;
		
		unsigned short elapsed = currentTime - startTime;
		startTime = currentTime;
		/*sprintf(fpsString, "elapsed : %d\n", elapsed);
		OutputDebugStringA(fpsString);*/
		oneSecond -= elapsed;
		count++;
		if(oneSecond < 0 )
		{
			sprintf(fpsString, "FPS : %d\n", count);
			OutputDebugStringA(fpsString);
			count = 0;
			oneSecond = 1000;
		}
			
    }
	delete fpsString;

    CleanupDevice();

    return ( int )msg.wParam;
}


//--------------------------------------------------------------------------------------
// Register class and create window
//--------------------------------------------------------------------------------------
HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow )
{
    // Register class
    WNDCLASSEX wcex;
    wcex.cbSize = sizeof( WNDCLASSEX );
    wcex.style = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc = WndProc;
    wcex.cbClsExtra = 0;
    wcex.cbWndExtra = 0;
    wcex.hInstance = hInstance;
    wcex.hIcon = LoadIcon( hInstance, ( LPCTSTR )IDI_TUTORIAL1 );
    wcex.hCursor = LoadCursor( NULL, IDC_ARROW );
    wcex.hbrBackground = ( HBRUSH )( COLOR_WINDOW + 1 );
    wcex.lpszMenuName = NULL;
    wcex.lpszClassName = L"TutorialWindowClass";
    wcex.hIconSm = LoadIcon( wcex.hInstance, ( LPCTSTR )IDI_TUTORIAL1 );
    if( !RegisterClassEx( &wcex ) )
        return E_FAIL;

    // Create window
    g_hInst = hInstance;
    RECT rc = { 0, 0, 1024, 768 };
    AdjustWindowRect( &rc, WS_OVERLAPPEDWINDOW, FALSE );
    g_hWnd = CreateWindow( L"TutorialWindowClass", L"Direct3D 11 Tutorial 7", WS_OVERLAPPEDWINDOW,
                           CW_USEDEFAULT, CW_USEDEFAULT, rc.right - rc.left, rc.bottom - rc.top, NULL, NULL, hInstance,
                           NULL );
    if( !g_hWnd )
        return E_FAIL;

    ShowWindow( g_hWnd, nCmdShow );

    return S_OK;
}




//--------------------------------------------------------------------------------------
// Create Direct3D device and swap chain
//--------------------------------------------------------------------------------------
HRESULT InitDevice()
{
    HRESULT hr = S_OK;

    RECT rc;
    GetClientRect( g_hWnd, &rc );
    UINT width = rc.right - rc.left;
    UINT height = rc.bottom - rc.top;

    UINT createDeviceFlags = 0;
#ifdef _DEBUG
    createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif

    D3D_DRIVER_TYPE driverTypes[] =
    {
        D3D_DRIVER_TYPE_HARDWARE,
        D3D_DRIVER_TYPE_WARP,
        D3D_DRIVER_TYPE_REFERENCE,
    };
    UINT numDriverTypes = ARRAYSIZE( driverTypes );

    D3D_FEATURE_LEVEL featureLevels[] =
    {
        D3D_FEATURE_LEVEL_11_0,
        D3D_FEATURE_LEVEL_10_1,
        D3D_FEATURE_LEVEL_10_0,
    };
    UINT numFeatureLevels = ARRAYSIZE( featureLevels );

    DXGI_SWAP_CHAIN_DESC sd;
    ZeroMemory( &sd, sizeof( sd ) );
    sd.BufferCount = 1;
    sd.BufferDesc.Width = width;
    sd.BufferDesc.Height = height;
    sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    sd.BufferDesc.RefreshRate.Numerator = 60;
    sd.BufferDesc.RefreshRate.Denominator = 1;
    sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    sd.OutputWindow = g_hWnd;
    sd.SampleDesc.Count = 1;
    sd.SampleDesc.Quality = 0;
    sd.Windowed = TRUE;

    for( UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++ )
    {
        g_driverType = driverTypes[driverTypeIndex];
		//g_driverType = D3D_DRIVER_TYPE_REFERENCE;
        hr = D3D11CreateDeviceAndSwapChain( NULL, g_driverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels,
                                            D3D11_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice, &g_featureLevel, &g_pImmediateContext );
        if( SUCCEEDED( hr ) )
            break;
    }
    if( FAILED( hr ) )
        return hr;

    // Create a render target view
    ID3D11Texture2D* pBackBuffer = NULL;
    hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), ( LPVOID* )&pBackBuffer );
    if( FAILED( hr ) )
        return hr;

    hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRenderTargetView );
    pBackBuffer->Release();
    if( FAILED( hr ) )
        return hr;

    // Create depth stencil texture
    D3D11_TEXTURE2D_DESC descDepth;
    ZeroMemory( &descDepth, sizeof(descDepth) );
    descDepth.Width = width;
    descDepth.Height = height;
    descDepth.MipLevels = 1;
    descDepth.ArraySize = 1;
    descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
    descDepth.SampleDesc.Count = 1;
    descDepth.SampleDesc.Quality = 0;
    descDepth.Usage = D3D11_USAGE_DEFAULT;
    descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
    descDepth.CPUAccessFlags = 0;
    descDepth.MiscFlags = 0;
    hr = g_pd3dDevice->CreateTexture2D( &descDepth, NULL, &g_pDepthStencil );
    if( FAILED( hr ) )
        return hr;

    // Create the depth stencil view
    D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
    ZeroMemory( &descDSV, sizeof(descDSV) );
    descDSV.Format = descDepth.Format;
    descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
    descDSV.Texture2D.MipSlice = 0;
    hr = g_pd3dDevice->CreateDepthStencilView( g_pDepthStencil, &descDSV, &g_pDepthStencilView );
    if( FAILED( hr ) )
        return hr;

    g_pImmediateContext->OMSetRenderTargets( 1, &g_pRenderTargetView, g_pDepthStencilView );
	DXDevice::Instance()->m_pOriginalRTV = g_pRenderTargetView;
	DXDevice::Instance()->m_pOriginalDSV = g_pDepthStencilView;
	DXDevice::Instance()->m_ScreenWidth = width;
	DXDevice::Instance()->m_ScreenHeight = height;
    // Setup the viewport
    D3D11_VIEWPORT vp;
    vp.Width = (FLOAT)width;
    vp.Height = (FLOAT)height;
    vp.MinDepth = 0.0f;
    vp.MaxDepth = 1.0f;
    vp.TopLeftX = 0;
    vp.TopLeftY = 0;
    g_pImmediateContext->RSSetViewports( 1, &vp );
	DXDevice::Instance()->m_pSODebug = new D3DStreamOutDbg();
	DXDevice::Instance()->m_pSODebug->InitStreamOutDbg(g_pd3dDevice, g_pImmediateContext);

	g_pVoxelTerrain = new VoxelTerrain(g_pd3dDevice, g_pImmediateContext);
	g_pVoxelTerrain->Init();

	D3D11_BUFFER_DESC bd;
    // Create the constant buffers
    bd.Usage = D3D11_USAGE_DEFAULT;
    bd.ByteWidth = sizeof(ViewMatrix);
    bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
    bd.CPUAccessFlags = 0;
	bd.MiscFlags = 0;
    hr = g_pd3dDevice->CreateBuffer( &bd, NULL, &g_matViewMatrixBuffer );
    if( FAILED( hr ) )
        return hr;
    
    bd.ByteWidth = sizeof(CBChangeOnResize);
    hr = g_pd3dDevice->CreateBuffer( &bd, NULL, &g_matProjectionMatrixBuffer );
    if( FAILED( hr ) )
        return hr;
    // Initialize the view matrix

    ViewMatrix viewMatrix;
    //ViewMatrix.mView = XMMatrixTranspose( g_View );
	g_pCamera = new Camera(width, height);
	g_pCamera->Init();
	viewMatrix.mView = g_pCamera->getViewMatrix();

    g_pImmediateContext->UpdateSubresource( g_matViewMatrixBuffer, 0, NULL, &viewMatrix, 0, 0 );

    // Initialize the projection matrix

    CBChangeOnResize cbChangesOnResize;
	cbChangesOnResize.mProjection = g_pCamera->getProjectionMatrix();
    g_pImmediateContext->UpdateSubresource( g_matProjectionMatrixBuffer, 0, NULL, &cbChangesOnResize, 0, 0 );


    /*hr = g_pd3dDevice->QueryInterface(__uuidof(ID3D11InfoQueue), (LPVOID*)&g_pInfoQueue);
    if (SUCCEEDED(hr))
    {
            g_pInfoQueue->ClearStoredMessages();
    }*/

	if( 0 )
	{
		ID3D11RasterizerState* pRSWireFrame; 
		D3D11_RASTERIZER_DESC RSWireFrameDesc; 
		ZeroMemory(&RSWireFrameDesc, sizeof(D3D11_RASTERIZER_DESC));
		RSWireFrameDesc.FillMode = D3D11_FILL_WIREFRAME; 
		RSWireFrameDesc.CullMode = D3D11_CULL_NONE;
		g_pd3dDevice->CreateRasterizerState ( &RSWireFrameDesc , &pRSWireFrame );
		g_pImmediateContext->RSSetState ( pRSWireFrame ); 
	}

    return S_OK;
}


//--------------------------------------------------------------------------------------
// Clean up the objects we've created
//--------------------------------------------------------------------------------------
void CleanupDevice()
{
    if( g_pImmediateContext ) g_pImmediateContext->ClearState();
    
    if( g_matViewMatrixBuffer ) g_matViewMatrixBuffer->Release();
	if( g_matProjectionMatrixBuffer ) g_matProjectionMatrixBuffer->Release();

	if( g_pVoxelTerrain ) g_pVoxelTerrain->Release();
    
    if( g_pDepthStencil ) g_pDepthStencil->Release();
    if( g_pDepthStencilView ) g_pDepthStencilView->Release();
    if( g_pRenderTargetView ) g_pRenderTargetView->Release();
    if( g_pSwapChain ) g_pSwapChain->Release();
    if( g_pImmediateContext ) g_pImmediateContext->Release();
    if( g_pd3dDevice ) g_pd3dDevice->Release();
	cleanDInput();
}


//--------------------------------------------------------------------------------------
// Called every time the application receives a message
//--------------------------------------------------------------------------------------
LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam )
{
    PAINTSTRUCT ps;
    HDC hdc;
	
    // do something...

    switch( message )
    {
        case WM_PAINT:
            hdc = BeginPaint( hWnd, &ps );
            EndPaint( hWnd, &ps );
            break;

        case WM_DESTROY:
            PostQuitMessage( 0 );
            break;

        default:
            return DefWindowProc( hWnd, message, wParam, lParam );
    }

    return 0;
}


//--------------------------------------------------------------------------------------
// Render a frame
//--------------------------------------------------------------------------------------
void Render()
{
    // Update our time
    static float t = 0.0f;
    if( g_driverType == D3D_DRIVER_TYPE_REFERENCE )
    {
        t += ( float )XM_PI * 0.0125f;
    }
    else
    {
        static DWORD dwTimeStart = 0;
        DWORD dwTimeCur = GetTickCount();
        if( dwTimeStart == 0 )
            dwTimeStart = dwTimeCur;
        t = ( dwTimeCur - dwTimeStart ) / 1000.0f;
    }

    //
    // Clear the back buffer
    //
    float ClearColor[4] = { 0.0f, 0.125f, 0.3f, 1.0f }; // red, green, blue, alpha
    g_pImmediateContext->ClearRenderTargetView( g_pRenderTargetView, ClearColor );

    //
    // Clear the depth buffer to 1.0 (max depth)
    //
    g_pImmediateContext->ClearDepthStencilView( g_pDepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0 );

	ViewMatrix cbViewMatrix;
	cbViewMatrix.mView =  g_pCamera->getViewMatrix();
    g_pImmediateContext->UpdateSubresource( g_matViewMatrixBuffer, 0, NULL, &cbViewMatrix, 0, 0 );

	D3DPERF_BeginEvent(D3DCOLOR_RGBA(255,0,0,1), L"voxel");
	g_pVoxelTerrain->Render(g_matViewMatrixBuffer, g_matProjectionMatrixBuffer);
    
	D3DPERF_EndEvent();

    //
    // Present our back buffer to our front buffer
    //
    g_pSwapChain->Present( 0, 0 );
}


// this is the function that initializes DirectInput
void initDInput(HINSTANCE hInstance, HWND hWnd)
{
    // create the DirectInput interface
    DirectInput8Create(hInstance,    // the handle to the application
                       DIRECTINPUT_VERSION,    // the compatible version
                       IID_IDirectInput8,    // the DirectInput interface version
                       (void**)&din,    // the pointer to the interface
                       NULL);    // COM stuff, so we'll set it to NULL

    // create the keyboard device
    din->CreateDevice(GUID_SysKeyboard,    // the default keyboard ID being used
                      &dinkeyboard,    // the pointer to the device interface
                      NULL);    // COM stuff, so we'll set it to NULL

    din->CreateDevice(GUID_SysMouse,
                      &dinmouse,
                      NULL);

    // set the data formats
    dinkeyboard->SetDataFormat(&c_dfDIKeyboard);
    dinmouse->SetDataFormat(&c_dfDIMouse);

    // set the control you will have over the devices
    dinkeyboard->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);
    dinmouse->SetCooperativeLevel(hWnd, DISCL_NONEXCLUSIVE | DISCL_FOREGROUND);
}
// this is the function that gets the latest input data
void detect_input(void)
{
	float fMovementSensitivity = 0.1f;
	float fRotationSensitivity = 0.01f;
    // get access if we don't have it already
    dinkeyboard->Acquire();

    dinmouse->Acquire();

    // get the input data
    dinkeyboard->GetDeviceState(256, (LPVOID)keystate);
    dinmouse->GetDeviceState(sizeof(DIMOUSESTATE), (LPVOID)&mousestate);

	if(keystate[DIK_W] & 0x80)
	{
		g_pCamera->cameraPos += g_pCamera->cameraDirection * fMovementSensitivity;
	}
	if(keystate[DIK_S] & 0x80)
	{
		g_pCamera->cameraPos -= g_pCamera->cameraDirection * fMovementSensitivity;
	}
	if(keystate[DIK_A] & 0x80)
	{
		g_pCamera->cameraPos -= g_pCamera->GetSideVector() * fMovementSensitivity;
	}
	if(keystate[DIK_D] & 0x80)
	{
		g_pCamera->cameraPos += g_pCamera->GetSideVector() * fMovementSensitivity;
	}
	if(keystate[DIK_Q] & 0x80)
	{
		g_pCamera->cameraPos.y += fMovementSensitivity;
	}
	if(keystate[DIK_Z] & 0x80)
	{
		g_pCamera->cameraPos.y -= fMovementSensitivity;
	}

	if(mousestate.rgbButtons[0] & 0x80)
	{
		g_pCamera->m_fHorizontalAngle -= (float)mousestate.lX * fRotationSensitivity;
		

		g_pCamera->m_fVerticalAngle -= (float)mousestate.lY * fRotationSensitivity;
		if(g_pCamera->m_fVerticalAngle <=  -D3DX_PI/2.0f)
		{
			g_pCamera->m_fVerticalAngle =  -D3DX_PI/2.0f + 0.001f;
		}
		else if(g_pCamera->m_fVerticalAngle >=  D3DX_PI/2.0f)
		{
			g_pCamera->m_fVerticalAngle =  D3DX_PI/2.0f - 0.001f;
		}
	}
	if(false && (mousestate.lX != 0 || mousestate.lY != 0))
	{
		WCHAR wstr[200];
		wsprintf(wstr, L"%i %i\n", g_pCamera->m_fHorizontalAngle, g_pCamera->m_fVerticalAngle);
		OutputDebugString(wstr);
	}
	

}
// this is the function that closes DirectInput
void cleanDInput(void)
{
    dinkeyboard->Unacquire();    // make sure the keyboard is unacquired
	dinmouse->Unacquire();    // make sure the mouse in unacquired
    din->Release();    // close DirectInput before exiting
}